<%@page import="java.util.HashMap"%>
<%@page import="com.mconnect.msurvey.controller.ConfirmManager"%>
<%@page import="com.mconnect.msurvey.controller.UserManager"%>
<%@page import="com.mconnect.msurvey.controller.DevelopingLanguagesManager"%>
<%@page import="com.mconnect.msurvey.model.DevelopingLanguages"%>
<%@page import="com.mconnect.msurvey.model.TechnicalQuestions"%>
<%@page import="com.mconnect.msurvey.controller.TechnicalQuestionsManager"%>
<%@page import="com.mconnect.msurvey.model.SurveyPlan"%>
<%@page import="com.mconnect.msurvey.model.ResponderRecommended"%>
<%@page import="com.mconnect.msurvey.controller.RecommendedManager"%>
<%@page import="com.mconnect.msurvey.controller.CategoryManager"%>
<%@page import="com.mconnect.msurvey.model.Questions"%>
<%@page import="com.mconnect.msurvey.controller.QuestionsManager"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="com.mconnect.msurvey.controller.PlanManager"%>
<%@page import="com.mconnect.msurvey.model.User"%>
<%@page import="com.mconnect.msurvey.model.Responder"%>
<%@page import="com.mconnect.msurvey.controller.ResponderManager"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<style>
            .errorMessage{
	  		color: red;
	  		font-style: italic;
	  		font-size: large;
	  		}
	  		
	  		.ui-accordion-content{
	  			height: 200px;
	  		}
	  		
			table.center{
				margin:0 auto;
			}
			div.center{
				margin:0 auto;
				text-align: center;
				
			}
			div#users-contain { width: 350px; margin: 20px 0; }
			div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
			div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
			
		label, input { display:block; }
		input.text { margin-bottom:12px; width:95%; padding: .4em; }
		fieldset { padding:0; border:0; margin-top:25px; }
		h1 { font-size: 1.2em; margin: .6em 0; }
		div#users-contain { width: 775px; margin-left: auto; margin-right: auto;  text-align: left; font-family: Arial; }
		.ui-dialog .ui-state-error { padding: .3em; }
		.validateTips { border: 1px solid transparent; padding: 0.3em; }
		
		div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
		th#jaca1 { border: 1px solid #eee; padding: .6em 10px; text-align: left; text-align: center;}
		td#jaca1 { border: 1px solid #eee; padding: .2em 2px; text-align: left; text-align: center;}
		th{color: black;}
</style>
<script src="js/jQuery/jquery-1.8.2.js"></script>
	<script src="js/jQuery/external/jquery.bgiframe-2.1.2.js"></script>
	<script src="js/jQuery/ui/jquery.ui.core.js"></script>
	<script src="js/jQuery/ui/jquery.ui.widget.js"></script>
	<script src="js/jQuery/ui/jquery.ui.mouse.js"></script>
	<script src="js/jQuery/ui/jquery.ui.button.js"></script>
	<script src="js/jQuery/ui/jquery.ui.draggable.js"></script>
	<script src="js/jQuery/ui/jquery.ui.position.js"></script>
	<script src="js/jQuery/ui/jquery.ui.resizable.js"></script>
	<script src="js/jQuery/ui/jquery.ui.dialog.js"></script>
	<script src="js/jQuery/ui/jquery.ui.effect.js"></script>
	<script src="js/jQuery/ui/jquery.ui.accordion.js"></script>
	<script src="js/jQuery/ui/jquery.ui.datepicker.js" charset="utf-8"></script>
	
	<link rel="stylesheet" href="resources/css/ap.css">
	  <link rel="stylesheet" href="js/jQuery/demos.css">
	  <link rel="stylesheet" href="js/jQuery/themes/base/jquery.ui.all.css">
	  <link type="text/css" href="js/jQuery/css/smoothness/jquery-ui-1.8.17.custom.css" rel="Stylesheet" />
	  <link rel="stylesheet" href="resources/css/detail_style.css">

<script type="text/javascript">
$(function(){
	
	$.fx.speeds._default = 200; 
	$( "#surveyContent_dialog" ).dialog({ 
			autoOpen: true,
			width: 900,
			minWidth: 700,
			height: 700,
			show: "explode",	
			hide: "explode"	,
			close: function (){
				$('.ui-dialog').remove();
			}
	}); 
	$( "#opener" ).click(function() {	
		$( "#surveyContent_dialog" ).dialog( "open" );	
		return false; 
	}); 
	
	$("#closeDialog").click(function(){
		$("#surveyContent_dialog").dialog("close");
	});
	
	var pesel = $( "#c_pesel" );
	var note = $( "#c_note" );
	
	allFields = $( [] ).add( pesel ),
	tips = $( ".validateTips" ),
	message = $( ".messageTips" );
	
	function updateTips( t ) {
		tips
			.text( t )
			.addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 1500 );
		}, 500 );
	}
	
	
	function checkLengthPesel( o, n, min, max ) {
		if ( o.val().length > max || o.val().length < min) {
			o.addClass( "ui-state-error" );
			updateTips( "Pole " + n + " musi zawierać 11 cyfr.");
			return false;
		} else {
			return true;
		}
	}
	
	function checkLength( o, n, min, max ) {
		if ( o.val().length > max || o.val().length < min) {
			o.addClass( "ui-state-error" );
			updateTips( "Pole " + n + " musi zawierać co najmniej " + min + " znaków.");
			return false;
		} else {
			return true;
		}
	}
	
	function checkNumber( o, n ) {
		var regEx = /[0-9 -()+]+$/;  
		if ( !o.val().match(regEx)) {
			o.addClass( "ui-state-error" );
			updateTips( "Pole " + n + " musi zawierać same cyfry.");
			return false;
		} else {
			return true;
		}
	}
	
	function checkPeselUnique(o) {
		var result = new Boolean();
		var dataString = 'pesel=' + o.val();
		
			  	$.ajax({
			        url: 'JsonServlet?' + dataString,
			        type: 'GET',
			        async: false,
			        cache: false,
			        timeout: 30000,
			        error: function(){
			            return true;
			        },
			        success: function(data){
			        	$.each(data, function(klucz, wartosc) {
			        		var checkJson = wartosc;
							if ( checkJson == 'true') {
								result = true;
							}else{
								o.addClass( "ui-state-error" );
								updateTips( "Podany pesel istnieje w bazie danych.");
								result = false;
							}
						});
			        	return false;
			        }
			    });
		
		return result;
	}
	
	
	$( "#dialog-form" ).dialog({
		autoOpen: false,
		height: 300,
		width: 350,
		modal: true,
		buttons: {
			"Zapisz": function() {
				var bValid = true;
				allFields.removeClass( "ui-state-error" );
				
				bValid = bValid && checkLengthPesel( pesel, "Pesel", 11, 11 ) && checkNumber(pesel, "Pesel") && checkPeselUnique(pesel);
				var pesels = pesel.val();
				var id_confirm = $( "#id_confirm" ).val();
				var id_responder = $( "#id_responder" ).val();
				var id_user =  $( "#id_user" ).val();
				
				if ( bValid ) {
				$.post(
						'savePesel.action',
						{
							pesel: pesels, id_responder : id_responder, id_confirm : id_confirm, id_user : id_user
						},
						function (content) {
							$('#msg').html(content);
							alert("Zapisano!");
							$( "#surveyContent_dialog" ).dialog("close");
							return false;
						}
					);
					$( this ).dialog( "close" );
					document.getElementById("create-confirm").disabled = true;
					
				}
				
			},
			"Anuluj": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.removeClass( "ui-state-error" );
		}
	});

	$( "#create-confirm" )
		.button()
		.click(function() {
			$( "#dialog-form" ).dialog( "open" );
		});
	
	$( "#create-notConfirm" )
	.button()
	.click(function() {
		$( "#dialog-form2" ).dialog( "open" );
	});
	
	
	$( "#dialog-form2" ).dialog({
		autoOpen: false,
		height: 300,
		width: 350,
		modal: true,
		buttons: {
			"Zapisz": function() {
				var bValid = true;
				allFields.removeClass( "ui-state-error" );
				
				bValid = bValid && checkLength( note, "Notatka", 1, 255 );
				var notes = note.val();
				var id_confirm = $( "#id_confirm" ).val();
				var id_responder = $( "#id_responder" ).val();
				var id_user =  $( "#id_user" ).val();
				
				if ( bValid ) {
				$.post(
						'saveNote.action',
						{
							note: notes, id_responder : id_responder, id_confirm : id_confirm, id_user : id_user
						},
						function (content) {
							$('#msg').html(content);
							alert("Zapisano!");
							$( "#surveyContent_dialog" ).dialog("close");
							return false;
						}
					);
					$( this ).dialog( "close" );
					document.getElementById("create-confirm").disabled = true;
					
				}
				
			},
			"Anuluj": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.removeClass( "ui-state-error" );
		}
	});
	
	$( "#create-recommend" )
	.button()
	.click(function() {
		$( "#recommend-form" ).dialog( "open" );
	});
	
	$( "#recommend-form" ).dialog({
		autoOpen: false,
		height: 300,
		width: 790,
		modal: true,
		buttons: {
			"Zapisz": function() {
				var id_responder = $( "#id_responder" ).val();
				var id_confirm = $( "#id_confirm" ).val();
				var phoneStr = '';
				var recommendTab = $('#recommendTable :input').serializeArray();
				var dataString = {
						id_responder : id_responder, id_confirm : id_confirm
				};
				var check = false;
				
				for(var i in recommendTab){
					
				    var nazwa = recommendTab[i].name;
				    if(typeof dataString[nazwa] == 'undefined'){
				    	dataString[nazwa] = new Array();
				    }
				    	
				    var ilosc = dataString[nazwa].length;
				    dataString[nazwa][ilosc] = recommendTab[i].value;
				    
				    if(ilosc >= 1 &&  (recommendTab[i].value).length >= 0){
						check = true;		
				    }
				    
				}
				var dataString2 = {};
				if(check){
					for(var i in recommendTab){
						 var nazwa = recommendTab[i].name;
						    if(typeof dataString2[nazwa] == 'undefined'){
						    	dataString2[nazwa] = new Array();
						    }
						    	
						    var ilosc2 = dataString2[nazwa].length;
						    dataString2[nazwa][ilosc2] = recommendTab[i].value;
						   
						if(ilosc2 > 0){
							if(check == true && recommendTab[i].name == 'recommendFirstname' && (recommendTab[i].value).length == 0){
						    	phoneStr += "Imie nie może być puste \n";
						   	}
							if(check == true && recommendTab[i].name == 'recommendedLastname' && (recommendTab[i].value).length == 0){
						    		phoneStr += "Nazwisko nie może być puste \n";
						    }	
							if(check == true && recommendTab[i].name == 'recommendedPhone' && (recommendTab[i].value).length == 0){
							    	phoneStr += "Telefon nie może być pusty \n";
							}
							var W = /^[0-9]{9}$/;
							if(check == true && recommendTab[i].name == 'recommendedPhone' && !(recommendTab[i].value).match(W)){
						    	phoneStr += "Telefon musi posiadac 9 cyfr \n";
							}
						}
					}
				}
				if(phoneStr == ''){
					$.post(
							'saveRecommendConfirm.action',
								dataString,
							function (content) {
								$('#msg').html(content);
								return false;
							}
						)
						.success(function() {alert("Zapisano!"); $('#recommendTable :input').val('');})
			            .error(function() { alert("Wystapil blad!"); })
			            .complete(function() { $( "#recommend-form" ).dialog( "close" ); });
				}else{
					alert("Wystapily nastepujace bledy: \n" + phoneStr);
				}
				
			},
			"Anuluj": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.removeClass( "ui-state-error" );
		}
	});
	
});
</script>

<script type="text/javascript">
		function removeRow(then) {
			$(then).parents('tr').remove();
		}
		function recommendTable_addRow() {
			var content1 = $('#recommendTable').find('.prototype').html();
			$('#recommendTable').find('.content').append('<tr class="last">'+content1+'</tr>');
			return $('#recommendTable').find('.content').find('tr.last');
		}
		
	</script>  

<%
	request.setCharacterEncoding("utf-8");
	String firstname = request.getParameter("firstname");
	String lastname =request.getParameter("lastname");
	int id_confirm = Integer.parseInt(request.getParameter("id_confirm"));
	int id_responder = Integer.parseInt(request.getParameter("id_responder"));
	int confirmUser = Integer.parseInt(request.getParameter("confirmUser"));
	int peselUser = 0;
	String pesel = "nie podano", datePesel = "nie podano", confirmUserStr = "", peselUserStr = "nie podano", note="";
	
	ConfirmManager cM = new ConfirmManager();
	HashMap<String, String> peselMap = cM.getPeselInfoByIdResponder(id_responder);
	if(peselMap.containsKey("pesel")) pesel = peselMap.get("pesel");
	if(peselMap.containsKey("data")) datePesel = peselMap.get("data");
	if(peselMap.containsKey("peselUser")) peselUser = Integer.parseInt(peselMap.get("peselUser"));
	if(peselMap.containsKey("note")) note = peselMap.get("note");
	
	UserManager uM = new UserManager();
	HashMap<String, String> userMap = uM.getNameOfUserByIdUser(confirmUser, peselUser);
	if(userMap.containsKey("confirmUser")) confirmUserStr = userMap.get("confirmUser");
	if(userMap.containsKey("peselUser")) peselUserStr = userMap.get("peselUser");
	
	User user = (User)session.getAttribute("admin");
	if(user == null){ %>
		<jsp:forward page="loginAdminForm.jsp"></jsp:forward>
	<%} %>
	
<div style="display: none; z-index: 1006; outline: 0px none; position: absolute; height: auto; width: 1024px; top: 100px; left: 158.5px;" class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable ui-resizable" tabindex="-1" role="dialog" aria-labelledby="ui-dialog-title-dialog"><div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix"><span class="ui-dialog-title" id="ui-dialog-title-dialog">Dialog Title</span><a href="#" class="ui-dialog-titlebar-close ui-corner-all" role="button"><span class="ui-icon ui-icon-closethick">close</span></a></div>
	<div id="surveyContent_dialog" title="Szczegóły" class="calendarCallback ui-dialog-content ui-widget-content" style="width: auto; min-height: 60.4px; height: auto; position: relative;" scrolltop="0" scrollleft="0">
		    <div style="width: 800px;  " class="center">
    	<div style="float: right; margin-right: 10px;">
    		
    	</div>
    	<div id="users-contain" class="ui-widget" >	
			<div id="d_all">
		      <div id="d_top1">
		     
		             <div class="d_a" style="width: 130px;">
		              <div class="a" >Imie i nazwisko</div>
		             </div>
		             <div class="d_b" style="width: 150px;">
		                <div class="b"><%= firstname + " " + lastname %></div>
		             </div>
		             <div class="d_a" style="width: 65px;">
		                <div class="a">Telefon</div>
		             </div>
		             <div class="d_b">
		                <div class="b"><%=request.getParameter("phone") %></div>
		             </div>
		             <div class="d_a" style="width: 65px;">
		                <div class="a">e-mail</div>
		             </div>
		             <div class="d_b">
		                <div class="b"><a style="color: white" href="mailto:<%=request.getParameter("mail") %>"><%=request.getParameter("mail") %></a></div>
		             </div>
		        
		      </div>
		      
		      <div id="d_bottom" style="min-height: 450px;">
		        <div id="d_bottom_txt" style="margin-top: 20px;">
		        	<table style="color: black; width: 600px;">
		        		<tr>
		        			<td id="left">Data spotkania</td>
		        			<td id="right"><%= request.getParameter("date") %></td>
		        		</tr>
		        		<tr>
		        			<td id="left">Godzina spotkania</td>
		        			<td id="right"><%= request.getParameter("time") %></td>
		        		</tr>
		        		<tr>
		        			<td id="left">Data kontaktu</td>
		        			<td id="right"><%= request.getParameter("confirmDate") %></td>
		        		</tr>
		        		<tr>
		        			<td id="left">Osoba dzwoniąca</td>
		        			<td id="right"><%= confirmUserStr %></td>
		        		</tr>
		        		<tr>
		        			<td id="left">Pesel</td>
		        			<td id="right"><%= pesel%></td>
		        		</tr>
		        		<tr>
		        			<td id="left">Data zapisania peselu</td>
		        			<td id="right"><%= datePesel %></td>
		        		</tr>
		        		<tr>
		        			<td id="left">Osoba zapisująca pesel</td>
		        			<td id="right"><%= peselUserStr %></td>
		        		</tr>
		        		<tr>
		        			<td id="left">Notatka</td>
		        			<td id="right">
		        				<div style="overflow:auto; max-width: 350px; max-height: 100px; ">
		        					<%= note %>
		        				</div>
		        			</td>
		        		</tr>
		        		<%if(pesel.equals("nie podano")){ %>
		        		<tr>
		        			<td colspan="2">
		        				<div class="d_aBack" style="width: 180px;  background-color: green; margin-left: -5px;" >
					        		<button  id="create-recommend" style="color: black; font-weight: bold; width: 180px; font-size: 11px; " >Dodaj Polecenie </button>
					       	 	</div>
		        			</td>
		        		</tr>
		        		<%} %>
		        	</table>
		      </div>
		    	<div class="center">
		    		<div style="width:700px; float: left; margin-top: 40px;">
		    		
		    			<% if("nie podano".equals(pesel)){ %>
					    	<div class="d_aBack" style="width: 180px; margin-left: 100px;" >
					        	<button  id="create-confirm" style="color: black; font-weight: bold; width: 175px;" >Zapisz pesel</button>
					        </div>
					         <div class="d_aBack" style=" margin-bottom: 10px; width: 175px;"  >
				        		<div class="a"><a href="#" style="text-decoration: none; display: block; text-align: center; color: white; font-weight: bold;" id="closeDialog">Anuluj</a></div>
				        	</div>
				        	<div class="d_aBack" style="width: 180px;" >
					        	<button  id="create-notConfirm" style="color: black; font-weight: bold; width: 175px;" >Nie zapisuj peselu</button>
					        </div>
				        <%}else{ %>
				        	</div>
					         	<div class="d_aBack" style="margin-left: 35%; margin-bottom: 10px; width: 180px;"  >
				        	<div class="a"><a href="#" style="text-decoration: none; display: block; text-align: center; color: white; font-weight: bold;" id="closeDialog">Anuluj</a></div>
				        </div>
				        <%} %>
				        
				       
			        </div>
			        <input type="hidden" id="id_responder" value="<%=id_responder %>">
					<input type="hidden" id="id_confirm" value="<%=id_confirm %>">
					<input type="hidden" id="id_user" value="<%=user.getId_user() %>">
					
			        <div id="dialog-form" title="Podaj pesel respondenta">
			        <p class="validateTips">Wszystkie pola są obowiązkowe.</p>
						<form id="form">
						<fieldset>
							<label for="c_pesel">Pesel</label>
							<input type="text" id="c_pesel"  class="text ui-widget-content ui-corner-all" />
						</fieldset>
						</form>
					</div>
					<div id="dialog-form2" title="Podaj przyczynę">
			        <p class="validateTips">Wszystkie pola są obowiązkowe.</p>
						<form id="form">
						<fieldset>
							<label for="c_note">Notatka</label>
							<textarea rows="5" cols="40"  id="c_note"  class="text ui-widget-content ui-corner-all"></textarea>
						</fieldset>
						</form>
					</div>
					
					<div id="recommend-form" title="Dodaj polecenie">
			        <p class="validateTips">Wszystkie pola są obowiązkowe.</p>
			        <div id="users-contain" class="ui-widget"  >
			        <table id="recommendTable" class="ui-widget ui-widget-content"  style="text-align: center; margin-top: 20px; width: 600px;">
						<thead >
							
							<tr class="ui-widget-header ">
								<th colspan="2"></th>
								<th align="center">Imię</th>
						        <th align="center">Nazwisko</th>
						        <th align="center">Numer telefonu</th>
						        <th align="center">e-mail</th>
						        <th></th>
							</tr>
						</thead>
						<tbody class="content">
							<tr style="display:none;" class="prototype">
								<td colspan="2"></td>
								 <td><input type="text" value="" name="recommendFirstname" class="required" id="AccordionField"/></td> 
				                 <td><input type="text" value="" name="recommendedLastname" /></td>
				                 <td><input type="text" value="" name="recommendedPhone"/></td>
				                 <td><input type="text" value="" name="recommendedMail"/></td>
								<td><a title="Usuń" onclick="removeRow(this)" href="#"><img src="resources/images/delete.png" /></a></td>
											
							</tr>
							<tr >
								<td colspan="2">Osoby z polecenia</td>
								<td><input type="text" value="" name="recommendFirstname"/></td> 
				                 <td><input type="text" value="" name="recommendedLastname"/></td>
				                 <td><input type="text" value="" name="recommendedPhone"/></td>
				                 <td><input type="text" value="" name="recommendedMail"/></td>
								<td style="width: 25px;"><a title="Dodaj" onclick="recommendTable_addRow()" href="#"><img src="resources/images/add.png" /></a></td>
							</tr>
						</tbody>
					</table>
					</div>
						
					</div>
					
				</div>
		  </div>
	
	</div>	
    </div>		
	</div>
<div class="ui-resizable-handle ui-resizable-n" style="z-index: 1000;"></div><div class="ui-resizable-handle ui-resizable-e" style="z-index: 1000;"></div><div class="ui-resizable-handle ui-resizable-s" style="z-index: 1000;"></div><div class="ui-resizable-handle ui-resizable-w" style="z-index: 1000;"></div><div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se ui-icon-grip-diagonal-se" style="z-index: 1000;"></div><div class="ui-resizable-handle ui-resizable-sw" style="z-index: 1000;"></div><div class="ui-resizable-handle ui-resizable-ne" style="z-index: 1000;"></div><div class="ui-resizable-handle ui-resizable-nw" style="z-index: 1000;"></div><div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"><div class="ui-dialog-buttonset"><button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text"></span></button><button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text"></span></button></div></div></div>
	